import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import {
  getToken,
  getIsHome,
  getAdminSwitch,
  removeAdminSwitch
} from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login"]; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start();
  // set page title
  document.title = getPageTitle(to.meta.title);
  // 确定是否登录
  const hasToken = getToken();
  //判断是否存在动态路由--------------------------------------------
  const hasRoles = store.getters.routes && store.getters.routes.length > 0;
  if (hasToken) {
    // 登录过
    if (to.path === "/login") {
      next();
      NProgress.done();
    } else {
      // 未登录过
      if (hasRoles) {
        //存在动态路由时--------------------------------------------
        next();
      } else {
        //不存在动态路由时--------------------------------------------
        try {
          //获取路由--------------------------------------------
          const params = {
            isHome: getIsHome()
          };
          const asyncRoutes = await store.dispatch(
            "menu/generateRoutes",
            params
          );
          router.addRoutes(asyncRoutes);
          if (getAdminSwitch() == 1) {
            removeAdminSwitch();
            next(`${asyncRoutes[0].path}`);
          } else {
            next(to.path);
          }
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch("user/resetToken");
          Message.error(error || "Has Error");
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    //没有登录令牌
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登入页面时直接进入
      next();
    } else {
      // 没有在免登录页时不进登录页
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
